package buru.server.netty.mvc;

import buru.server.netty.NettyHandlerJerseyContainer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpContentCompressor;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.glassfish.jersey.server.ApplicationHandler;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.mvc.internal.MvcBinder;

/**
 * Auth: bruce-sha
 * Date: 2015/4/1
 */
public class MVCServer {


    public static void main(String[] args) throws Exception {

        ResourceConfig rcf = new MVCResourceConfig();
        rcf.registerClasses(FreemarkerResource.class);
//        rcf.packages("info.ibruce");

        try (AutoNioEventLoopGroup bossGroup = new AutoNioEventLoopGroup();
             AutoNioEventLoopGroup workerGroup = new AutoNioEventLoopGroup()) {

            ServerBootstrap bootstrap = new ServerBootstrap()
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new HttpResponseEncoder());
                            pipeline.addLast(new HttpRequestDecoder());
                            pipeline.addLast(new HttpContentCompressor());
                            pipeline.addLast(new NettyHandlerJerseyContainer(new ApplicationHandler(rcf,new MvcBinder())));
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            Channel channel = bootstrap.bind(9527).sync().channel();

//            Logs.log("service started on port {}", port);

            channel.closeFuture().sync();
        }
    }

    static class AutoNioEventLoopGroup extends NioEventLoopGroup implements AutoCloseable {

        public AutoNioEventLoopGroup() {
            super(Runtime.getRuntime().availableProcessors());
        }

        @Override
        public void close() throws Exception {
            shutdownGracefully();
        }
    }
}
